//
//  PersonalPicker.m
//  CQWU_OA
//
//  Created by WisdomsLab on 14-1-19.
//  Copyright (c) 2014年 Juchui. All rights reserved.
//

#import "PersonalPicker.h"

@interface PersonalPicker ()<
UITableViewDataSource,
UITableViewDelegate,
UITextFieldDelegate>{
    NSArray *dataSource;
    NSArray *datas;
    NSMutableArray *pickerDatas;
    NSArray *py;
}

@property(strong,nonatomic) NSArray *dataSource;
@property(strong,nonatomic) NSArray *datas;
@property(strong,nonatomic) NSMutableArray *pickerDatas;
@property(strong,nonatomic) NSArray *py;

@end

@implementation PersonalPicker

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
- (BOOL)prefersStatusBarHidden {
    return NO;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
#endif

@synthesize delegate;
@synthesize searchText;
@synthesize btnFinish;
@synthesize btnSearch;
@synthesize tableView;

@synthesize datas;
@synthesize dataSource;
@synthesize pickerDatas;
@synthesize py;

UIButton *btnGroup;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    py = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"];
    
    dataSource = [[NSArray alloc] init];
    pickerDatas = [[NSMutableArray alloc] initWithCapacity:0];
    
    datas = @[@{
                    @"id":@1,
                    @"name":@"张三",
                    @"department":@"现教中心"
                    },
                   @{
                       @"id":@2,
                       @"name":@"李四",
                       @"department":@"教务处"
                       },
                   @{
                       @"id":@3,
                       @"name":@"王麻子",
                       @"department":@"现教中心"
                       },
                   @{
                       @"id":@4,
                       @"name":@"王老五",
                       @"department":@"现教中心"
                       },
                   @{
                       @"id":@5,
                       @"name":@"王明",
                       @"department":@"现教中心"
                       },
                   @{
                       @"id":@6,
                       @"name":@"张大毛",
                       @"department":@"教务处"
                       }];
    
    searchText.placeholder = @"请输入姓名";
    btnGroup = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44.0f, 28.0f)];
    [btnGroup setBackgroundColor:[UIColor blueColor]];
    [btnGroup setTitle:@"姓名" forState:UIControlStateNormal];
    [btnGroup setTitle:@"部门" forState:UIControlStateSelected];
    btnGroup.selected = NO;
    [btnGroup addTarget:self action:@selector(toggleGroupAction:) forControlEvents:UIControlEventTouchUpInside];
    searchText.leftView = btnGroup;
    searchText.leftViewMode = UITextFieldViewModeAlways;
    searchText.delegate = self;
    
    [btnSearch addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.tableFooterView = [[UIView alloc] init];
    
    btnFinish.enabled = NO;
    
    [self addObserver:self forKeyPath:@"pickerDatas" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self doSearch];
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"PersonalInfoCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    if(nil == cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:dataSource[indexPath.row]];
    cell.textLabel.text = dic[@"name"];
    cell.detailTextLabel.text = dic[@"department"];
    return cell;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return py;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self willChangeValueForKey:@"pickerDatas"];
    [pickerDatas addObject:dataSource[indexPath.row]];
    [self didChangeValueForKey:@"pickerDatas"];
}

#pragma mark - Actions
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:@"pickerDatas"]){
        if(0 < pickerDatas.count){
            btnFinish.enabled = YES;
        }else{
            btnFinish.enabled = NO;
        }
    }
}

-(void)toggleGroupAction:(UIButton *)btn{
    btn.selected = !btn.selected;
    if(btn.selected){
        searchText.placeholder = @"请输入部门名称";
    }else{
        searchText.placeholder = @"请输入姓名";
    }
    [self doSearch];
}

-(void)searchAction:(UIButton *)btn{
    [self doSearch];
}

-(void)doSearch{
    NSString *searchKey = searchText.text;
    if(0 < searchKey.length){
        NSPredicate *predicate;
        if(btnGroup.selected){
            predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"department CONTAINS[d] '%@'",searchKey]];
        }else{
            predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"name CONTAINS[d] '%@'",searchKey]];
        }
        dataSource = [[NSArray alloc] initWithArray:[datas filteredArrayUsingPredicate:predicate]];
    }else{
        dataSource = datas;
    }
    
    [tableView reloadData];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}

- (IBAction)cancelAction:(id)sender {
    if(delegate && [delegate respondsToSelector:@selector(personalPickerControllerDidCancel:)]){
        [delegate personalPickerControllerDidCancel:self];
    }
}

- (IBAction)finishAction:(id)sender {
    if(delegate && [delegate respondsToSelector:@selector(personalPickerController:didFinishPickingWithInfo:)]){
        [delegate personalPickerController:self didFinishPickingWithInfo:pickerDatas];
    }
}
@end
